<template>
	<div class="page-info">
		<div class="search">
			<div class="search-box">
				<a-form
					:model="searchInfo"
					:label-col="labelCol"
					:wrapper-col="wrapperCol"
				>
					<a-row :gutter="24">
						<a-col :span="6">
							<a-form-item
								:name="labelMap['phone'].name"
								:label="labelMap['phone'].label"
							>
								<a-input
									style="width: 90%; margin-left: 8px"
									v-model:value="searchInfo.phone"
									:placeholder="'请填写' + labelMap['phone'].label"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['code'].name"
								:label="labelMap['code'].label"
							>
								<a-input
									style="width: 90%; margin-left: 8px"
									v-model:value="searchInfo.code"
									:placeholder="'请填写' + labelMap['code'].label"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['source'].name"
								:label="labelMap['source'].label"
							>
								<a-select
									style="width: 90%; margin-left: 8px"
									ref="select"
									v-model:value="searchInfo.source"
									:placeholder="'请选择' + labelMap['source'].label"
									:options="sourceList"
									:allowClear="true"
								>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col style="text-align: right; margin-bottom: 20px">
							<a-space>
								<a-button type="primary" @click="query"> 查找</a-button>
								<a-button type="primary" @click="cancelQuery">清空</a-button>
							</a-space>
						</a-col>
					</a-row>
				</a-form>
			</div>
		</div>
		<div class="button" style="margin: 10px">
			<a-space>
				<a-button type="primary" @click="editUserInfo('add')">新增</a-button>
				<a-button type="primary" @click="exportUserInfo">导出</a-button>
				<a-button type="primary" danger @click="batchDelUserInfo"
					>删除</a-button
				>
			</a-space>
		</div>
		<div class="content">
			<a-table
				:dataSource="dataSource"
				:columns="columns"
				:loading="loading"
				:row-key="(record) => record.id"
				:pagination="pagination"
				@change="handleTableChange"
				:scroll="{ y: 420, x: 'max-content' }"
				:row-selection="rowSelection"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'operation'">
						<a-space>
							<a-button
								type="primary"
								size="small"
								@click="editUserInfo('update', record.id)"
								>编辑</a-button
							>
							<a-popconfirm
								title="确认删除?"
								ok-text="确认"
								cancel-text="取消"
								@confirm="delUserInfo(record.id)"
								@cancel="cancel"
							>
								<a-button type="primary" size="small" danger>删除</a-button>
							</a-popconfirm>
						</a-space>
						<span></span>
					</template>
					<template v-else-if="column.key === 'status'">
						<a-tag
							:key="record.status"
							:color="record.status === '1' ? '#87d068' : 'red'"
						>
							{{ record.status === '1' ? '激活' : '失效' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'wechatOpenid'">
						<a-tag
							:key="record.status"
							:color="record.wechatOpenid ? '#87d068' : 'red'"
						>
							{{ record.wechatOpenid ? '已关联' : '未关联' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'avatar'">
						<a-image
							v-if="record?.personAvatar?.preUrl"
							:width="150"
							:src="record?.personAvatar?.preUrl"
						/>
					</template>
					<template v-else-if="column.key === 'self'">
						<a-tag
							:key="record.status"
							:color="record.self ? '#87d068' : 'red'"
						>
							{{ record?.self ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'hiddenPhone'">
						<a-tag
							:key="record.hiddenPhone"
							:color="record.hiddenPhone ? '#87d068' : 'red'"
						>
							{{ record?.hiddenPhone ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'singleFlag'">
						<a-tag
							:key="record.singleFlag"
							:color="record.singleFlag ? '#87d068' : 'red'"
						>
							{{ record?.singleFlag ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'partnerFlag'">
						<a-tag
							:key="record.partnerFlag"
							:color="record.partnerFlag ? '#87d068' : 'red'"
						>
							{{ record?.partnerFlag ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'membershipFlag'">
						<a-tag
							:key="record.membershipFlag"
							:color="record.membershipFlag ? '#87d068' : 'red'"
						>
							{{ record?.membershipFlag ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'membershipName'">
						{{ record.membershipName || '' }}
					</template>
					<template v-else-if="column.key === 'matchmakerFlag'">
						<a-tag
							:key="record.matchmakerFlag"
							:color="record.matchmakerFlag ? '#87d068' : 'red'"
						>
							{{ record?.matchmakerFlag ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'idCardName'">
						{{ record.identityVerificationVo?.name }}
					</template>
					<template v-else-if="column.key === 'idCardNumber'">
						{{ record.identityVerificationVo?.idCardNumber }}
					</template>
					<template v-else-if="column.key === 'source'">
						{{ getSourceName(record.source) }}
					</template>
					<!-- 会员有效期：仅会员时显示 -->
					<template v-else-if="column.key === 'membershipExpireTime'">
						<span v-if="record.membershipFlag">{{
							record.userMembershipInfoVo?.endTime ?
								dayjs(record.userMembershipInfoVo?.endTime).format('YYYY-MM-DD')
							:	'-'
						}}</span>
					</template>
					<!-- 红娘编码/职级：仅红娘时显示 -->
					<template v-else-if="column.key === 'matchmakerNo'">
						<span v-if="record.matchmakerFlag">{{
							record.matchmakerInfoVo?.no ?? ''
						}}</span>
					</template>
					<template v-else-if="column.key === 'matchmakerPositionLevelName'">
						<span v-if="record.matchmakerFlag">{{
							record.matchmakerInfoVo?.positionLevel || ''
						}}</span>
					</template>
					<!-- 合伙人类型/有效期：仅合伙人时显示 -->
					<template v-else-if="column.key === 'partnerTypeName'">
						<span v-if="record.partnerFlag">{{
							record.offlineServiceProviderVo?.partnerTypeName || ''
						}}</span>
					</template>
					<template v-else-if="column.key === 'partnerExpireTime'">
						<span v-if="record.partnerFlag">{{
							record.offlineServiceProviderVo?.endTime ?
								dayjs(record.offlineServiceProviderVo?.endTime).format(
									'YYYY-MM-DD',
								)
							:	'-'
						}}</span>
					</template>
				</template>
			</a-table>
			<UserInfoDetail
				ref="editInfo"
				:open="visible"
				:modelInfo="modelInfo"
				@handleOk="handleOk"
				@handleCancel="handleCancel"
			>
			</UserInfoDetail>
		</div>
	</div>
</template>
<script setup lang="ts">
import { columns, DataItem, getSourceName, ModelInfo, pageInfo, pagination, SearchInfo } from './userInfoListTs';
import { deleteUserInfo, exportUserInfoApi, getUserInfoPage } from '@/api/userInfo/userInfo/userInfoTs';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

const labelCol = ref({ span: 5 });
const wrapperCol = ref({ span: 19 });

let rowIds = [] as any;

const rowSelection = ref({
	checkStrictly: false,
	onChange: (
		selectedRowKeys: (string | number)[],
		selectedRows: DataItem[],
	) => {
		rowIds = selectedRowKeys;
	},
	onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
		console.log(record, selected, selectedRows);
	},
	onSelectAll: (
		selected: boolean,
		selectedRows: DataItem[],
		changeRows: DataItem[],
	) => {
		console.log(selected, selectedRows, changeRows);
	},
});

const labelMap = ref<any>({
	username: { name: 'username', label: '用户名' },
	password: { name: 'password', label: '密码（加密存储）' },
	phone: { name: 'phone', label: '手机号码' },
	code: { name: 'code', label: '用户编码' },
	status: { name: 'status', label: '用户状态 (active=活跃, inactive=不活跃)' },
	wechatOpenid: { name: 'wechatOpenid', label: '微信OpenID' },
	wechatUnionid: {
		name: 'wechatUnionid',
		label: '微信UnionID（跨平台统一标识）',
	},
	avatar: { name: 'avatar', label: '头像id' },
	self: { name: 'self', label: '仅自己可见（1：是，0：否）' },
	wechatBindTime: { name: 'wechatBindTime', label: '绑定微信账号的时间' },
	introUserId: { name: 'introUserId', label: '推荐人id' },
	codeNum: { name: 'codeNum', label: 'code数' },
	source: { name: 'source', label: '来源' },
});

let searchInfo = ref<SearchInfo>({});

let sourceList: any[] = [
	{ label: '官方来源', value: 1 },
	{ label: '红娘', value: 2 },
	{ label: '婚介所', value: 3 },
];

const cancelQuery = (): void => {
	searchInfo.value = {};
};

const query = (): void => {
	getUserInfoListPage(searchInfo.value, pagination.value);
};

const handleTableChange = (pagination): void => {
	getUserInfoListPage(searchInfo.value, pagination);
};

const delUserInfo = (ids: string): void => {
	deleteUserInfo(ids).then((res) => {
		if (res.code == '200') {
			message.success((res && '删除' + res.message) || '删除成功！', 3);
			getUserInfoListPage(searchInfo.value, pagination.value);
		} else {
			message.error((res && res.message) || '删除失败！', 3);
		}
	});
};

const batchDelUserInfo = (): void => {
	let ids = '';
	if (rowIds && rowIds.length > 0) {
		rowIds.forEach((item: string) => {
			ids += item + ',';
		});
		ids = ids.substring(0, ids.length - 1);
	} else {
		message.warning('请先选择数据！', 3);
		return;
	}
	delUserInfo(ids);
};

let loading = ref<boolean>(false);

let dataSource = ref();

const cancel = (e: MouseEvent): void => {
	console.log(e);
};

const getUserInfoListPage = (param: SearchInfo, cur: pageInfo): void => {
	loading.value = true;
	getUserInfoPage(param, cur.current, cur.pageSize)
		.then((res) => {
			if (res.code == '200') {
				dataSource.value = res.data.records;
				pagination.value.current = res.data.current;
				pagination.value.pageSize = res.data.size;
				pagination.value.total = res.data.total;
			} else {
				message.error((res && res.message) || '查询列表失败！');
			}
		})
		.finally(() => {
			loading.value = false;
		});
};

const init = (): void => {
	//获取用户信息页面数据
	getUserInfoListPage(searchInfo.value, pagination.value);
};

init();

let visible = ref<boolean>(false);

let modelInfo = ref<ModelInfo>({});

//新增和修改弹窗
const editUserInfo = (type: string, id?: number): void => {
	if (type == 'add') {
		modelInfo.value.title = '新增明细';
		modelInfo.value.id = undefined;
	} else if (type == 'update') {
		modelInfo.value.title = '修改明细';
		modelInfo.value.id = id;
	}
	modelInfo.value.confirmLoading = true;
	visible.value = true;
};

const handleOk = (v: boolean): void => {
	visible.value = v;
	getUserInfoListPage(searchInfo.value, pagination.value);
};

const handleCancel = (v: boolean): void => {
	visible.value = v;
};

// 导出
const exportUserInfo = async (): Promise<void> => {
	try {
		const res = await exportUserInfoApi(searchInfo.value);
		const blob = new Blob([res.data], {
			type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
		});
		const url = window.URL.createObjectURL(blob);
		const a = document.createElement('a');
		a.href = url;
		a.download = `用户信息_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`;
		document.body.appendChild(a);
		a.click();
		document.body.removeChild(a);
		window.URL.revokeObjectURL(url);
	} catch (e) {
		message.error('导出失败');
	}
};
</script>
<style lang="scss" scoped></style>
